//
//  XSJUserAccountViewModel.swift
//  weiBo项目准备
//
//  Created by 鲜世杰 on 16/5/12.
//  Copyright © 2016年 鲜世杰. All rights reserved.
//

import UIKit

class XSJUserAccountViewModel: NSObject {
    
    static let sharedUserAccount: XSJUserAccountViewModel = XSJUserAccountViewModel()
    
    
    override init() {
        super.init()
        userAccount = XSJUserAocut.loadUserAccount()
    }
     var isLogin: Bool {
       
        return accessToken != nil
    }
    var accessToken: String? {
        
        
        guard let token = userAccount?.access_token else {
            return nil
        }
        
        let result = userAccount?.expiresDate?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending {
            return token
        } else {
            return nil
        }
        
    }
    
    //  保存用户对象
    var userAccount: XSJUserAocut?
    //  封装网络接口
    //  获取accesstoken
    func requestAccessToken(code: String, complete: (isSuccess: Bool)->()) {
        
        
        XSJNetWorkTools.sharedTools.requestAccessToken(code) { (response, error) -> () in
            if error != nil {
                print("网络请求异常")
                complete(isSuccess: false)
                return
            }
            
            //  代码执行到此 网络请求成功
            
            guard let dic = response as? [String: AnyObject] else {
                print("数据不是一个正确的json格式")
                complete(isSuccess: false)
                return
            }
            
            //  代码执行到此一定是字典
            let userAccount = XSJUserAocut(dic: dic)
//            print(userAccount)
            self.requestUserInfo(userAccount, complete: complete)
            
            
        }
        
    }
    //  获取用户信息
    func requestUserInfo(userAccount: XSJUserAocut, complete: (isSuccess: Bool)->()) {
        
        XSJNetWorkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
            
            if error != nil {
                print("网络请求异常")
                complete(isSuccess: false)
                return
            }
            //  判断json格式
            guard let dic = response as? [String: AnyObject] else {
                print("不是一个正确的json数据")
                complete(isSuccess: false)
                return
            }
            
            //  代码执行到此是一个正确的字典格式
            userAccount.name = dic["name"] as? String
            userAccount.avatar_large = dic["avatar_large"] as? String
            //  设置用户数据
            self.userAccount = userAccount
            //  归档数据
            let result = userAccount.saveUserAccount()
            //  才代表登陆成功
            if result {
                //  登陆成功
                complete(isSuccess: true)
            } else {
                complete(isSuccess: false)
            }
        }
    }
    
}
